<template>
	<view class="container-exercises">
		<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" v-if="!showView"></u-empty>
		<template v-if="showView">
			<view class="container-box">
				<!--进度条-->
				<progress-box :progress="progress"></progress-box>
				<!--题干-->
				<answer-stem :content="current.stem"></answer-stem>
				<!--工具栏-->
				<template v-if="isTypeOne">
					<answer-toolbar :current="current"></answer-toolbar>
				</template>
				<!--选择题-->
				<view v-if="isTypeOne" style="position: relative;">
					<view class="mask" v-if="showBlur" @click="hideMask"></view>
					<view class="list" :class="{'blur':showBlur}">
						<view v-for="(item,index) in current.select" :key="index" class="list-item">
							<view :class="{ 'active': item.active }" class="item" @click="handleClickItem(item,index)">
								<!-- {{ serialNumber[index] }}. {{ item.title }} -->
							<!-- <answer-stem :content="serialNumber[index]+'.'+item.title"></answer-stem> -->
								{{ serialNumber[index] }}.
								<answer-stem :content="item.title"></answer-stem>
							</view>
						</view>
					</view>
				</view>

				<!--填空选择题-->
				<view v-if="isTypeTwo">
					<scroll-view scroll-x="true" class="scroll-view-tab">
						<view class="tab-list">
							<view v-for="(item,index) in current.list" :key="index" class="list-item">
								<view class="item" :class="{'active' : index === subCurrentIndex }"
									@click="handleClickTab(item,index)">
									{{ index+1 }}
								</view>
							</view>
						</view>
					</scroll-view>
					<view style="position: relative;">
						<view class="mask" v-if="showBlur" @click="hideMask"></view>
						<view class="list" :class="{'blur':showBlur}">
							<view v-for="(item,index) in subCurrent.select" :key="index">
								<view :class="{ 'active' : item.active}" class="item"
									@click="handleClickSubItem(item,index)">
									{{ serialNumber[index] }}. {{ item.title }}
								</view>
							</view>
						</view>
					</view>
				</view>

				<!--选择答案解析-->
				<view v-if="showAnalysis">
					<answer-box :info="current"></answer-box>
					<template v-if="hasAnalysis">
						<answer-analysis :text="current.analysis_text" :video="current.analysis_video"></answer-analysis>
					</template>
					<template v-if="!hasVideo">
						<get-video-analysis @getVideo="getVideo" :isSendVideo="current.isSendVideo">
						</get-video-analysis>
					</template>

				</view>

				<!--填空答案解析-->
				<template v-if="isTypeTwo">
					<template v-if="showSubAnswer">
						<answer-box :info="subCurrent"></answer-box>
					</template>
					<template v-if="showSubAnalysis">
						<answer-analysis :text="current.analysis_text" :video="current.analysis_video"></answer-analysis>
					</template>
					<template v-if="!hasVideo">
						<get-video-analysis @getVideo="getVideo" :isSendVideo="current.isSendVideo">
						</get-video-analysis>
					</template>
				</template>
				<!---确定按钮-->
				<view class="button-commit" v-if="showCommit">
					<view class="light-button" @click="handleClickConmit">确定</view>
					<!-- <view class="gray-button" v-else>确定</view> -->
				</view>
			</view>
			<!--上一题-下一题-->
			<view class="change-answer-button" v-if="showPrevNext">
				<view class="button" @click="prev" v-if="showPrev">上一题</view>
				<view class="button" @click="next" v-if="showNext">下一题</view>
			</view>






			<!--课后练习答題卡-->
			<answer-card :list="answerCardList" @toNextAnswerPage="toNextAnswerPage" @resetSomePage="resetSomePage"
				@resetPage="resetPage" v-if="showAnswerCard" :isRightCard="isRightCard">
			</answer-card>
			<view class="show-card-btn" @click="showAnswerCard = true" v-if="showCardButton">
				<u-icon label="答题卡" labelColor="#9AB973" labelSize="12" labelPos="bottom" size="30"
					name="http://qiniu.disciplineeducation.com/studyIcons/card-icon.png"></u-icon>
			</view>
			<!--课前预习弹窗-->
			<popup-view v-if="showPopup" :content='popupContent' @onConfirm="onConfirm" @onCancel="onCancel">
			</popup-view>

			<!--答题完成提示-->
			<template v-if="showTips">
				<answer-tips :isRight="isRight"></answer-tips>
			</template>
		</template>

	</view>
</template>

<script>
	import AnswerCard from '@/pages/components/AnswerCard.vue'
	import PopupView from '@/pages/components/PopupView.vue'
	import GetVideoAnalysis from '@/pages/components/GetVideoAnalysis.vue'
	import AnswerAnalysis from '@/pages/components/AnswerAnalysis.vue'
	import AnswerStem from '@/pages/components/AnswerStem.vue'
	import AnswerToolbar from '@/pages/components/AnswerToolbar.vue'
	import ProgressBox from '@/pages/components/ProgressBox.vue'
	import AnswerTips from '@/pages/components/AnswerTips.vue'
	import AnswerBox from '@/pages/components/AnswerBox.vue'
	export default {
		components: {
			AnswerCard,
			PopupView,
			GetVideoAnalysis,
			AnswerAnalysis,
			AnswerStem,
			AnswerToolbar,
			ProgressBox,
			AnswerTips,
			AnswerBox
		},
		data() {
			return {
				imgUrl:'<img height="21px" width="161px" mode:"aspectFit" src="http://qiniu.disciplineeducation.com/word/20230220/15460478dpszc26m/image/154608hvbixn.jpg"/>',
				imageProp:{
					mode:'aspectFit',
					padding:20,
					lazyLoad:false
				},
				option: {},
				progress: { //进度条参数
					total: 20,
					current: 1,
					percent: 0
				},
				myAnswer: [], //我的答题,
				userAnswer: {},
				showCommit: false, //控制答题按钮显示隐藏
				showPrevNext: false, //控制上一题下一题按钮显示隐藏
				serialNumber: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
					'S'
				],
				active: true,
				current: {}, //当前题json
				currentIndex: 0, //当前题索引
				subCurrent: {}, //当前填空题
				subCurrentIndex: 0,
				info: { //模拟习题
					//list
				},
				showView: true,
				showBlur: true,
				isRightCard: false,
				showAnswerCard: false,
				showBeforeModal: false,
				answerCardList: [],
				popupContent: '您已完成课前预习，前往听课',
				showPopup: false,
				nextId: '',
				qualified: true,
				showTips: false,
				timmer: null,
				isRight: null,
				showCardButton: false
			}
		},
		onShareAppMessage(res) {
			return this.$utils.onShareAppMessage();
		},
		onLoad(option) {
			this.option = option;
			if (this.isWrong) {
				this.getWrongList();
				return false;
			}
			if (this.isBrush) {
				this.getBrushList();
				return false;
			}
			if (this.option.source == '1') {
				this.getData()
			}
		},
		computed: {
			hasVideo() {
				return this.current.analysis_video
			},
			showSubAnalysis() {
				return this.current.isAllAnswer && (this.current.analysis_text || this.current.analysis_video)
			},
			showAnalysis() {
				return this.current.type === 1 && this.current.isAnswer
			},
			isTypeTwo() {
				return this.current.type === 2
			},
			isTypeOne() {
				return this.current.type === 1
			},
			showSubAnswer() {
				return this.subCurrent.isAnswer
			},
			hasAnalysis() {
				return this.current.analysis_text || this.current.analysis_video
			},
			showPrev() {
				return this.progress.current > 0
			},
			showNext() {
				return this.progress.current + 1 != this.progress.total
			},
			//是物理刷题
			isBrush() {
				return this.option.source == '2' && this.option.sourceType === 'brush'
			},
			//错题刷题
			isWrong() {
				return this.option.source == '2' && this.option.sourceType === 'wrong'
			}
		},
		methods: {
			//物理刷题列表
			async getBrushList() {
				const res = await this.$http.get(`/wechatmini/brush-questions?course_ids=${this.option.ids}`)
				let list = res.data.list;
				if (list.length === 0) {
					this.showView = false;
					return false;
				}
				this.setField(res);
				// for(let i =0;i<list.lenght;i++){
				// 	if(list[i].question_id == res.data.current_question_id){
				// 		this.currentIndex = i;
				// 		break;
				// 	}
				// }
				this.info = res.data;
				this.initPage();
			},
			//错题刷题列表
			async getWrongList() {
				const res = await this.$http.get(`/wechatmini/error-questions?course_ids=${this.option.ids}`)
				let list = [];
				res.data.list.forEach(item => {
					let obj = item.question;
					obj['course_question_user_answer_record_id'] = item.course_question_user_answer_record_id;
					list.push(obj)
				})

				if (res.data.list.length === 0) {
					this.showView = false;
					return false;
				}
				let info = {
					data: {
						list
					}
				};
				this.setField(info);
				this.info = info.data;
				this.initPage();
			},
			//习题列表
			async getData() {
				const res = await this.$http.get(
					`/wechatmini/course-questions?course_question_set_id=${this.option.id}&question_category=${ this.option.type }`
				)
				if (res.data.list.length === 0) {
					this.showView = false;
					return false;
				}
				this.setField(res);
				this.info = res.data;
				this.initPage();
			},
			//错题销题&&提交答题
			async postData() {
				this.setIsRight();
				if (this.option.source == 2 && this.option.sourceType === 'wrong') {
					const res = await this.$http.post(`/wechatmini/error-question/repair`, {
						question_id: this.current.question_id,
						repair_answer: JSON.stringify(this.userAnswer),
						course_question_user_answer_record_id: this.current
							.course_question_user_answer_record_id
					})
					return false;
				}


				const res = await this.$http.post(`/wechatmini/course-question/answer`, {
					question_id: this.current.question_id,
					user_answer: JSON.stringify(this.userAnswer),
					source: this.option.source,
					course_user_answer_batch_id: this.info.course_user_answer_batch_id
				})



				if (this.info.list.length - 1 === this.currentIndex && this.option.source == 1) {
					this.onFinish();
				}

			},
			//最后一题完成
			async onFinish() {
				const res = await this.$http.post(
					`/wechatmini/course-question-set/${ this.option.id }/finish/${ this.option.type }`);
				this.getStudyResult()

			},
			//获取答题卡数据
			async getStudyResult() {
				const res = await this.$http.get(
					`/wechatmini/course-question-set/study-result?course_question_set_id=${this.option.id}&category=${ this.option.type }&course_user_answer_batch_id=${ this.info.course_user_answer_batch_id }`
				)
				//课后练习
				if (this.option.type == 3) {
					this.setAfter(res);
					return false;
				}
				//课前习题
				if (this.option.type == 1) {
					this.setBefore(res);
				}


			},
			//获取视频解析请求
			async getVideo() {
				const res = await this.$http.post(
					`/wechatmini/course-question/demand-analysis?course_question_id=${ this.current.question_id }`
				)
				if (res.code == 0) {
					this.current['isSendVideo'] = true;
				}
			},
			//保存刷题记录
			async saveBrushRecard() {
				const res = await this.$http.post(
					`/wechatmini/brush-question/position?question_id=${this.current.question_id}`, {
						selfLoading: true
					}
				)
			},
			//注入依赖字段，数据才能双向绑定
			setField(res) {
				res.data.list.forEach(item => {
					if (item.type == 1) {
						item['isAnswer'] = false;
						item['isRight'] = null;
						item['isSendVideo'] = null;
						item['myAnswer'] = null;
						item['active'] = false;
					}
					if (item.type == 2) {
						item.list.forEach(subItem => {
							subItem['isAnswer'] = false;
							subItem['isRight'] = null;
							subItem['isSendVideo'] = null;
							subItem['myAnswer'] = null;
							subItem['active'] = false;
							subItem['showBlur'] = true;
						})
						item['isAllAnswer'] = false;
					}
				})
			},
			//课前习题弹窗数据处理
			setBefore(res) {

				let list = [];
				let total = 0
				for (let key in res.data.study_result) {
					if (res.data.study_result[key] === 1) {
						list.push(res.data.study_result[key])
					}
					total = total + 1;
				}
				if (list.length > 0) {
					if (list.length / total * 100 >= 60) {
						this.qualified = true
						this.popupContent = "您已完成课前预习，前往听课"
					} else {
						this.qualified = false
						this.popupContent = "根据您的答题情况，请重新学习之前章节"
					}
				} else {
					this.qualified = false
					this.popupContent = "根据您的答题情况，请重新学习之前章节"
				}
				let self = this;
				this.timmer = setTimeout(() => {
					self.showPopup = true;
					clearTimeout(self.timmer);
				}, 1500)

			},
			//课后答题卡数据处理
			setAfter(res) {
				let self = this;
				this.nextId = res.data.course_question_set_id;
				let list = [];
				let _list = []
				for (let key in res.data.study_result) {
					list.push(res.data.study_result[key])
					_list.push({
						isRight: res.data.study_result[key] === 1 ? true : false
					})
				}
				this.isRightCard = list.every((item) => {
					return item === 1
				})
				this.answerCardList = _list;
				this.timmer = setTimeout(() => {
					self.showAnswerCard = true;
					self.showCardButton = true;
					clearTimeout(self.timmer);
				}, 1500)
			},
			//设置答题是否答对
			setIsRight() {
				let self = this;
				clearTimeout(this.timmer);
				let current = null;
				if (this.current.type == 1) {
					current = this.current
				} else if (this.current.type == 2) {
					current = this.subCurrent
				}

				if (current.rightAnswer.join(',') === current.myAnswer.join(',')) {
					current['isRight'] = true
					this.isRight = true;
				} else {
					current['isRight'] = false;
					this.isRight = false;
				}
				this.showTips = true;
				this.timmer = setTimeout(() => {
					self.showTips = false;
				}, 1000)
			},
			//提交数据 调用后台接口
			onCommit() {
				if (this.current.type === 1) {
					this.postData();
				}

				if (this.current.type === 2) {
					if (this.getSubIsAnswer()) {
						this.current['isAllAnswer'] = true;
						this.postData();
					} else {
						this.setIsRight();
					}
				}

			},
			//跳转下一题课前习题
			toNextAnswerPage() {
				if (this.nextId == 0) {
					uni.navigateBack();
					return false;
				}
				this.option.type = 1;
				this.option.id = this.nextId;
				this.showAnswerCard = false;
				this.getData();
			},
			//定位到某一题
			resetSomePage(index) {
				if (index !== -1) {
					this.currentIndex = index;
				} else {
					for (let i = 0; i < this.answerCardList.length; i++) {
						if (!this.answerCardList[i].isRight) {
							this.currentIndex = i;
							break;
						}
					}
				}
				this.subCurrentIndex = 0;
				this.initPage();
				this.showAnswerCard = false;
			},
			//重置习题
			resetPage() {
				this.showCardButton = false
				this.currentIndex = 0;
				this.subCurrentIndex = 0;
				this.getData();
				this.showAnswerCard = false;
			},
			//设置习题
			initPage() {
				let current = this.info.list[this.currentIndex];
				this.current = current;
				this.progress = {
					total: this.info.list.length,
					current: this.currentIndex,
					percent: (100 / this.info.list.length) * (this.currentIndex + 1)
				}
				if (current.type === 2) {
					this.subCurrent = current.list[this.subCurrentIndex];
					this.setSubAnswer()
				}
				this.changeBlur();
				this.changeButton();
				if (this.isBrush) {
					this.saveBrushRecard();
				}
			},
			//点击填空题序号
			handleClickTab(item, index) {
				this.subCurrentIndex = index;
				this.subCurrent = item
				this.changeButton();
				this.changeBlur();
			},
			//点击填空题答题选项
			handleClickSubItem(item, index) {
				if (this.subCurrent.isAnswer) {
					return false;
				}
				item.active = !item.active;
				this.$forceUpdate()
				this.changeButton();
			},

			//多选（不定向）
			handleMultipleChoice(item, index) {
				item.active = !item.active;
				this.setMyAnswer()
			},
			//单选（定向）
			handleSingleChoice(item, index) {
				this.current.select.forEach(ite => {
					ite.active = false;
				})
				item.active = true;
				this.setMyAnswer()
			},
			//点击选择题答题选项
			handleClickItem(item, index) {
				if (this.showCommit === false) {
					return false;
				}
				if (this.current.is_direct == 1) {
					this.handleSingleChoice(item, index)
				} else {
					this.handleMultipleChoice(item, index)
				}


			},
			//点击确定按钮
			handleClickConmit() {
				if (this.current.type === 1) {
					let isSelect = this.current.select.some((item) => {
						return item.active
					})
					if (!isSelect) {
						uni.showToast({
							title: '还没有答题呦~',
							icon: 'error'
						})
						return false;
					} else {
						this.current.isAnswer = true;
					}
					this.setMyAnswer();
					this.onCommit()
				}

				if (this.current.type === 2) {
					let select = this.subCurrent.select.filter((item) => {
						return item.active
					})
					if (select.length === 0) {
						uni.showToast({
							title: '还没有答题呦~',
							icon: 'error'
						})
						return false;
					}
					this.setSubAnswer();
					this.onCommit();
				}
				this.changeButton();

			},
			//获取填空题是否完成
			getSubIsAnswer() {
				let total = this.current.list.length;
				let select = this.current.list.filter(item => {
					return item.isAnswer
				})
				return total === select.length
			},
			//设置填空题选择题我的答案
			setSubAnswer() {
				let myAnswer = [];
				this.current.list[this.subCurrentIndex].select.forEach((item, index) => {
					if (item.active) {
						myAnswer.push(this.serialNumber[index].replace(/\s+/g, ""));
					}
				})
				let select = this.subCurrent.select.filter(item => {
					return item.active
				})
				if (select.length === 0) {
					this.subCurrent.isAnswer = false
				} else {
					this.subCurrent.isAnswer = true
				}
				this.subCurrent['myAnswer'] = myAnswer;
				this.userAnswer[this.subCurrent.subordinate_id] = myAnswer;
			},
			//选择题我的答案
			setMyAnswer() {
				let myAnswer = [];
				this.current.select.forEach((item, index) => {
					if (item.active) {
						myAnswer.push(this.serialNumber[index].replace(/\s+/g, ""))
					}
				})
				this.current['myAnswer'] = myAnswer;
				let user_answer = {};
				this.userAnswer = {
					[this.current.question_id]: myAnswer
				}
			},
			//返回上一页
			onReturn() {
				uni.navigateBack()
			},
			//判断显示哪个按钮
			changeButton() {
				if (this.current.type === 1) {
					console.log('2222')
					if (this.current.isAnswer) {
						this.showPrevNext = true;
						this.showCommit = false;

					} else {
						this.showPrevNext = false;
						this.showCommit = true
					}
				}

				if (this.current.type === 2) {
					if (this.getSubIsAnswer()) {
						this.showPrevNext = true;
						this.showCommit = false;
						return false;
					}

					if (this.subCurrent.isAnswer) {
						this.showPrevNext = false;
						this.showCommit = false;
						return false;
					}

					let select = this.subCurrent.select.filter(item => {
						return item.isAnswer
					})
					if (select.length > 0) {
						this.showPrevNext = true;
						this.showCommit = false;
					} else {
						this.showPrevNext = false;
						this.showCommit = true;
					}
				}


			},

			//点击下一题
			next() {
				if (this.info.list.length - 1 === this.currentIndex) {
					return false;
				}
				this.currentIndex = this.currentIndex + 1;
				this.initPage();
			},
			//点击上一题
			prev() {

				if (this.currentIndex === 0) {
					return false;
				}
				this.currentIndex = this.currentIndex - 1;
				this.initPage();
			},
			//隐藏模糊效果，隐藏遮罩层
			hideMask() {
				this.showBlur = false;
				if(this.current.type === 2){
					this.subCurrent.showBlur = false;
				}
			},
			//设置是否显示模糊效果
			changeBlur() {
				if (this.current.type === 1) {
					if (!this.current.isAnswer) {
						this.showBlur = true
					} else {
						this.showBlur = false
					}
				} else {
					if (this.subCurrent.showBlur) {
						this.showBlur = true
					} else {
						this.showBlur = false
					}
				}

			},
			//课前学习完成弹窗确定按钮
			onConfirm() {
				this.showPopup = false;
				if (this.qualified) {
					uni.redirectTo({
						url: `/pages/inclass/index?type=2&id=${ this.option.id }`,
					})
				} else {
					this.onReturn();
				}

			},
			//课前学习完成弹窗取消按钮
			onCancel() {
				this.showPopup = false;
			},

		}
	}
</script>

<style>
	page {
		height: 100%;
		overflow-y: hidden;
		overflow-x: hidden;
	}
</style>
<style scoped lang="scss">
	.container-box {
		padding: 20rpx;
		height: calc(100vh - 240rpx);
		overflow-y: scroll;
		-webkit-overflow-scrolling: touch;
	}

	.list {
		width: 100%;
		margin-top: 30rpx;
		max-height: calc(50vh - 150rpx);
		overflow: auto;
		-webkit-overflow-scrolling: touch;
		position: relative;

		.list-item {
			width: 100%
		}

		.item {
			border: 1rpx solid #acada8;
			border-radius: 3px;
			padding: 20rpx;
			color: #333;
			margin-bottom: 30rpx;
			cursor: pointer;
			display: flex;
			flex-direction: row;
			
			.content {
				width: 100% !important;
				// display: flex;
				justify-content:start;
				align-items:left
				
				///deep/ p img
			}
			.content /deep/ img{
				width: 40% !important;
				mode: 'scaleToFill';
				// justify-content:start
			}
		}

		.item.active {
			background-color: #d3dea4;
			border: 1px solid #bfc4ad;
			
		}
		
	}

	.button-commit {
		position: fixed;
		left: 0;
		// bottom:0;
		// padding-bottom: 40rpx;
		// padding-top: 40rpx;
		padding-top: 60rpx;
		width: 100%;

		button {
			width: 70%;
			margin: 0 auto;
			text-align: center;
			color: #fff;
			border-radius: 40rpx;
			border: none;
		}

		.light-button {
			background-color: #ccc6db;
			height: 80rpx;
			line-height: 80rpx;
			width: 80%;
			margin: 0 auto;
			border-radius: 40rpx;
			text-align: center;
			color: #fff;
		}

		.gray-button {
			background-color: #cdd0d9;
		}

	}

	.change-answer-button {
		position: fixed;
		background-color: #f0f0f0;
		width: 100%;
		text-align: center;
		padding-bottom: 50rpx;
		bottom: 0rpx;
		left: 0;
		z-index: 99;

		.button {
			width: 120rpx;
			height: 120rpx;
			display: inline-block;
			line-height: 120rpx;
			background-color: #ebbed5;
			text-align: center;
			color: #fff;
			border-radius: 50%;
			border: none;
			font-size: 30rpx;
			margin: 0 60rpx
		}

		.button:last-child {
			background-color: #f1ccb1;
		}
	}





	.scroll-view-tab {
		margin-top: 30rpx;
		padding: 20rpx 0;
		border-top: 6rpx solid #abc3c5;
		border-bottom: 6rpx solid #abc3c5
	}

	.tab-list {
		display: flex;

		.item {
			width: 60rpx;
			height: 60rpx;
			text-align: center;
			line-height: 60rpx;
			border-radius: 50%;
			background-color: #dcd6f8;
			margin-right: 20rpx;
			color: #fff;
		}

		.item.active {
			background-color: #fbdbc4;
		}
	}

	.empoty {
		text-align: center;
		margin-top: 20%
	}

	.blur {
		-webkit-filter: blur(5px);
		filter: blur(5px);
	}

	.mask {
		position: absolute;
		top: 0rpx;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 10;
		background: rgba(0, 0, 0, 0);
	}

	.show-card-btn {
		position: fixed;
		z-index: 100;
		bottom: 20rpx;
		right: 20rpx
	}
</style>
